<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-09-29
 * Time: 13:48
 */

namespace backend\controllers;


use app\models\CtiConfig;
use common\helps\Tools;
use common\helps\XmlTool;
use yii\filters\VerbFilter;

class CtiManagerConfigController  extends CtiManagerController
{

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * 拿到字典的配置文件
     */
    public function actionGetConfig(){
        $ctiConfig = new CtiConfig();
        $res = $ctiConfig->find()->andWhere(isset($_POST['type'])?['type'=>$_POST['type']]:"")->andWhere(isset($_POST['parent_type'])?['parent_type'=>$_POST['parent_type']]:"")->asArray()->all();
        return $this->jsonEncode($res);
    }

    /**
     * 保存字典的配置文件
     */
    public function actionSaveConfig(){
        $ctiConfig = new CtiConfig();
        $ctiConfigModel = $ctiConfig->find()->where(['parent_type'=>$_POST['parent_type']])->one();
        $res = $ctiConfigModel->updateAttributes(['remark'=>json_encode($_POST['remark'])]);
        $res1 = $this->saveFreeSwitchVars();
        $res2 = $this->saveFreeSwitchDialplan();
        return $this->dealFD('',($res&&$res1&&$res2)==true?1:0);
    }

    /**
     * 保存freeswitch配置文件 vars.xml 文件
     */
    public function saveFreeSwitchVars(){
        $remark = $_POST['remark'];
        $freeswitchHttp = $remark['http'];
        $freeswitchDomain = $remark['crmDomain'];
        $crmDomain = $freeswitchHttp.'://'.$freeswitchDomain;
        $search1 = ['include','X-PRE-PROCESS','type="allWebSite"','data="allWebSite=[\s\S]*"'];
        $replace1 = ['include','X-PRE-PROCESS','type="allWebSite"','data="allWebSite='.$crmDomain.'"'];
        $res1 = $this->replaceXmlFileConfig($remark['root'].'/'.$remark['path'].'/conf/vars.xml',$search1,$replace1,false);
        $search2 = ['include','X-PRE-PROCESS','type="allWebDomain"','data="allWebDomain=[\s\S]*"'];
        $replace2 = ['include','X-PRE-PROCESS','type="allWebDomain"','data="allWebDomain='.$remark['imsDomain'].'"'];
        $res2 = $this->replaceXmlFileConfig($res1,$search2,$replace2,false,true);
        $search3 = ['include','X-PRE-PROCESS','type="domain"','data="domain=[\s\S]*"'];
        $replace3 = ['include','X-PRE-PROCESS','type="domain"','data="domain='.$remark['domain'].'"'];
        $res3 = $this->replaceXmlFileConfig($res2,$search3,$replace3,false,true);
        $this->ftpSaveFile($remark,'/conf/vars.xml',$res3);
        return 1;
    }

    /**
     * 保存freeswitch配置文件 /conf/dialplan/default.xml 文件
     */
    public function saveFreeSwitchDialplan(){
        //修改配置 录音文件所在目录1
        $node = ['include','context',['extension'=>['name'=>'IMSOutbound']],'condition',['action'=>['application'=>'export','data'=>'execute_on_answer']]];
        $remark = $_POST['remark'];
        $replace = '/'.$remark['recordPath'].'/${strftime(%Y-%m-%d)}/${destination_number}/${caller_id_number}_${strftime(%H-%M-%S)}.wav';
        $res3 = XmlTool::replaceXml('/conf/dialplan/default.xml',$node,'record_session '.$replace);
        //修改配置 录音文件所在目录2
        $node = ['include','context',['extension'=>['name'=>'IMSInbound']],'condition',['action'=>['application'=>'export','data'=>'execute_on_answer']]];
        $remark = $_POST['remark'];
        $replace = '/'.$remark['recordPath'].'/${strftime(%Y-%m-%d)}/${destination_number}/${caller_id_number}_${strftime(%H-%M-%S)}.wav';
        $res4 = XmlTool::replaceXml('/conf/dialplan/default.xml',$node,'record_session '.$replace);
        //修改配置 是否录音1
        $node = ['include','context',['extension'=>['name'=>'IMSOutbound']],'condition',['action'=>['id'=>'IMSOutbound_record_session','data']]];
        $remark = $_POST['remark'];
        $replace_ = '/'.$remark['recordPath'].'/${strftime(%Y-%m-%d)}/${destination_number}/${caller_id_number}_${strftime(%H-%M-%S)}.wav';
        $replace = $remark['luyin']=='false'?'':('execute_on_answer=record_session '.$replace_);
        $res1 = XmlTool::replaceXml('/conf/dialplan/default.xml',$node,$replace);
        //修改配置 是否录音2
        $node = ['include','context',['extension'=>['name'=>'IMSInbound']],'condition',['action'=>['id'=>'IMSInbound_record_session','data']]];
        $remark = $_POST['remark'];
        $replace_ = '/'.$remark['recordPath'].'/${strftime(%Y-%m-%d)}/${destination_number}/${caller_id_number}_${strftime(%H-%M-%S)}.wav';
        $replace = $remark['luyin']=='false'?'':('execute_on_answer=record_session '.$replace_);
        $res2 = XmlTool::replaceXml('/conf/dialplan/default.xml',$node,$replace);
        //最后刷新default.xml文档 Freeswitch的命令是
        $this->execFSBgapi("reloadxml");
        return $res1&&$res2&&$res3&&$res4;
    }

    /**
     * 设置字典的配置文件
     */
    public function actionUpdateConfig(){
        /**
         * 一般的格式为
         *[
         *  callcenter_strategy => long-idel-agent
         *  callcenter_style => callback
         * ]
         */
        $results = false;
        foreach ($_POST as $k=>$v){
            $ctiConfig = new CtiConfig();
            $res = $ctiConfig->find()->andWhere(['type'=>$k])->one();
            $result = $res->updateAttributes(['en_name'=>$v]);
            //替换掉相应的配置
            $file = $this->path.'conf\\autoload_configs\\callcenter.conf.xml';
            $search = ['queue name="support@default"','param','name="strategy"','value="([\s\S]*)"'];
            $replace = ['queue name="support@default"','param','name="strategy"','value="'.$v.'"'];
            if ($result){
                $res = $this->replaceXmlFileConfig($file,$search,$replace);//将内容更新到freeswitch配置文件中
                $this->writeToFile($file,$res);
            }
            $results = $result || $results;
        }
        if ($results){
            $this->execFSBgapi("reload mod_callcenter");
        }
        return $results;
    }
}